#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "newwindow.h"

#include <iostream>

#include <QWebEngineView>
#include <QWebChannel>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonArray>


MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "7777");

    // 与地图网页交互
    _myChannel = new MyChannel(this);						// 与网页js通讯的对象

    QWebChannel* web_channel = new QWebChannel(this);
    web_channel->registerObject("qtChannel", _myChannel);    // 向QWebChannel对象注册Qt对象

    page = ui->webengineview->page();
    page->setWebChannel(web_channel);
    ui->webengineview->load(QUrl("qrc:/smap/mymap_ba.html"));   // 加载页面

    // 绑定飞行器移动与停止的按钮事件
    // QObject::connect(ui->btn_move, &QPushButton::clicked, this, &MainWindow::MoveToEast);

    //与服务器进行交互
    _tcpclient = new Client(this);      // 网络连接对象

    // 与子窗口交互
    // recv affairs
    configWindow = new newWindow(this);
    // send affairs
    sendWindow = new NewWindSend(this);


    // 将服务器发送过来的消息显示在文本框
    void(Client:: * clientSiganl)(QString) = &Client::SendWndData;		//函数指针，限定作用域
    void(MainWindow:: * wndSlot)(QString) = &MainWindow::WndDsplyData;	//函数指针，限定作用域
    QObject::connect(_tcpclient, clientSiganl, this, wndSlot);
    // 将新窗口发送过来的消息发送给服务器
    void(NewWindSend:: * newWndSendSiganl)(QString) = &NewWindSend::SendMainWndData;		//函数指针，限定作用域
    void(MainWindow:: * wndSendSlot)(QString) = &MainWindow::SendToServer;	//函数指针，限定作用域
    QObject::connect(sendWindow, newWndSendSiganl, this, wndSendSlot);


    // prepare to move
    planeIsMove = false;
    // prepare to move plane
    planeSelfIsMove = false;
    // recv affairs
    recvData = "";
    recvMsgCnt = 0;
    recvWndIsOpen = false;
    // send affairs
    sendWndIsOpen = false;
    // timer to show cpu info
    mTime = new QTimer();
    connect(mTime,&QTimer::timeout,this,[=]()
            {
                ShowMachineInfo();
            });
    mTime->start(1000);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::WndDsplyData(QString data)
{
    // show recv reminder
    recvMsgCnt += 1;
    ui->btn_recv->setText(QString("+%1").arg(recvMsgCnt));

    // Mack up data to show.
    QDateTime dateTime = QDateTime::currentDateTime();		//获取系统当前的时间
    QString dt = dateTime.toString("hh:mm:ss");             //格式化时间
    QString str = QString("[%1] %2\n").arg(dt, data);
    recvData = QString("%1 \n %2").arg(str,recvData);

}
void MainWindow::on_btn_recv_clicked()
{
    recvWndIsOpen = !recvWndIsOpen;
    if(recvWndIsOpen){
        // pop a window
        configWindow->show();
        // show text received
        configWindow->NewWndDsplyData(recvData);

    }else{
        // clear recv reminder
        recvData = "";
        ui->btn_recv->setText("");
        recvMsgCnt = 0;
        configWindow->close();
    }
}

void MainWindow::on_btnMoveIcon_clicked()
{
    if (!planeIsMove) {
        qDebug() << "Enter on_btnMoveIcon_clicked()";

        // // create icons

        ui->btnMoveIcon->setIconSize(QSize(20,20));
        QIcon iconMoveStop(":/smap/pics/movestop.png");
        ui->btnMoveIcon->setIcon(iconMoveStop);
        // ui->btnMoveIcon->setStyleSheet("QPushButton {background-image: url(:/smap/pics/movestop.icon)}");
        // ui->btnMoveIcon->repaint();
        qDebug() << "Set Icon";

        // 向东移动
        _myChannel->MoveToEast(page);
        qDebug() << "Exit on_btnMoveIcon_clicked()";

        planeIsMove = !planeIsMove;
    }
    else {
        qDebug() << "Enter on_btnMoveIcon_clicked stop";

        // // create icons
        ui->btnMoveIcon->setIconSize(QSize(20,20));
        QIcon iconMovetoRight(":/smap/pics/movetoright.png");
        ui->btnMoveIcon->setIcon(iconMovetoRight);
        // ui->btnMoveIcon->setStyleSheet("QPushButton {background-image: url(:/smap/pics/movetoright.icon)}");
        // ui->btnMoveIcon->repaint();
        qDebug() << "Set Icon stop";

        // 向东移动停止
        _myChannel->StopMoveToEast(page);
        qDebug() << "Exit on_btnMoveIcon_clicked  stop";


        planeIsMove = !planeIsMove;
    }
}


void MainWindow::on_btn_moveplaneicon_clicked()
{
    if (!planeSelfIsMove) {
        qDebug() << "Enter on_btn_moveplaneicon_clicked()";

        // // create icons

        ui->btn_moveplaneicon->setIconSize(QSize(20,20));
        QIcon iconMoveStop(":/smap/pics/movestop.png");
        ui->btn_moveplaneicon->setIcon(iconMoveStop);
        // ui->btn_moveplaneicon->setStyleSheet("QPushButton {background-image: url(:/smap/pics/movestop.icon)}");
        // ui->btn_moveplaneicon->repaint();
        qDebug() << "Set Icon";

        // 向东移动
        _myChannel->PlaneMoveToEast(page);
        qDebug() << "Exit on_btn_moveplaneicon_clicked()";

        planeSelfIsMove = !planeSelfIsMove;
    }
    else {
        qDebug() << "Enter on_btn_moveplaneicon_clicked stop";

        // // create icons
        ui->btn_moveplaneicon->setIconSize(QSize(20,20));
        QIcon iconMovetoRight(":/smap/pics/planemove.png");
        ui->btn_moveplaneicon->setIcon(iconMovetoRight);
        // ui->btn_moveplaneicon->setStyleSheet("QPushButton {background-image: url(:/smap/pics/movetoright.icon)}");
        // ui->btn_moveplaneicon->repaint();
        qDebug() << "Set Icon stop";

        // 向东移动停止
        _myChannel->PlaneStopMoveToEast(page);
        qDebug() << "Exit on_btn_moveplaneicon_clicked  stop";


        planeSelfIsMove = !planeSelfIsMove;
    }
}

void MainWindow::on_btn_send_clicked()
{
    sendWndIsOpen = !sendWndIsOpen;
    if(sendWndIsOpen){
        // pop a window
        sendWindow->show();
        sendWindow->setVisible(true);
    }else{
        sendWindow->close();
    }
}

/// <summary>
/// recv from new wnd and send to server
/// </summary>
void MainWindow::SendToServer(QString data){
    bool wrtState = _tcpclient->UavSendData(data);
    sendWindow->SetWrtState(wrtState);
}


void MainWindow::ShowMachineInfo(){
    statusex.dwLength=sizeof(statusex);
    GlobalMemoryStatusEx(&statusex); // mem info
    GetSystemInfo(&systemInfo); // cpu info

    QString dataCpu;
    dataCpu = QString("CPU Architecture: %1 \nNumber of Processors: %2 \nMemory total: %3M \nMemory reserved: %4M \nMemory use ratio: %5\%").arg(
                    (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ? "AMD64" : "x86")).arg(
                       systemInfo.dwNumberOfProcessors).arg(
                       statusex.ullTotalPhys/1024/1024).arg(
                       statusex.ullAvailPhys/1024/1024).arg(
                       statusex.dwMemoryLoad
                       );

    ui->text_cpu->setPlainText(dataCpu);
}

// reconnet to server
void MainWindow::on_btn_reconn_clicked()
{
    _tcpclient->Reconnect();
}

